package com.aliyun.handler;

import com.aliyun.core.AliyunContext;
import com.aliyun.core.emun.AliyunContextType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

@Slf4j
public class AliyunContextHolder implements InitializingBean, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static final String prefix = "aliyun-context-";

    public static AliyunContext getContext(AliyunContextType contextType){
        Assert.notNull(contextType,"contextType is null");
        String type = contextType.getType();
        return applicationContext.getBean(prefix + type, AliyunContext.class);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug("AliyunContextHolder init");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AliyunContextHolder.applicationContext = applicationContext;
    }
}
